﻿using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MesProjectWinform.Public.Common;
using Newtonsoft.Json.Linq;
using MesProjectWinform.BasicData.Entity;
using Newtonsoft.Json;
using System.Net.Http;
using System.Web;
using System.IO;
using DevExpress.XtraSplashScreen;

namespace MesProjectWinform.BasicData.基础实现.chanpin
{
    public partial class chanpins : DevExpress.XtraEditors.XtraForm
    {
        // API服务端口号
        private const string ApiBaseUrl = "http://47.110.243.157:5052/";
        
        // 分页参数
        private int pageIndex = 1;
        private int pageSize = 2;
        private int totalCount = 0;

        public chanpins()
        {
            InitializeComponent();
            
            // 设置窗体居中显示
            this.StartPosition = FormStartPosition.CenterScreen;

            // 初始化分页控件
            InitPagination();

            // 初始化物料群组下拉框
            InitMaterialGroupComboBox();
            
            // 设置GridView列
            ConfigureGridViewColumns();

            // 初始化时加载数据
            LoadData();
        }

        /// <summary>
        /// 初始化分页控件
        /// </summary>
        private void InitPagination()
        {
            // 创建页大小下拉框
            ComboBoxEdit pageSizeCombo = new ComboBoxEdit();
            pageSizeCombo.Properties.Items.AddRange(new object[] { 2, 10, 20, 50, 100 });
            pageSizeCombo.SelectedIndex = 0;
            pageSizeCombo.Width = 60;
            pageSizeCombo.EditValueChanged += PageSizeCombo_EditValueChanged;

            // 创建首页按钮
            SimpleButton btnFirst = new SimpleButton();
            btnFirst.Text = "首页";
            btnFirst.Width = 60;
            btnFirst.Click += BtnFirst_Click;

            // 创建尾页按钮
            SimpleButton btnLast = new SimpleButton();
            btnLast.Text = "尾页";
            btnLast.Width = 60;
            btnLast.Click += BtnLast_Click;

            // 创建页码标签
            LabelControl lblPageInfo = new LabelControl();
            lblPageInfo.Name = "lblPageInfo";
            lblPageInfo.Text = "0/0";
            lblPageInfo.AutoSize = true;
            lblPageInfo.Padding = new Padding(5, 3, 5, 0);

            // 创建总记录数标签
            LabelControl lblTotalCount = new LabelControl();
            lblTotalCount.Name = "lblTotalCount";
            lblTotalCount.Text = "共0条记录";
            lblTotalCount.AutoSize = true;
            lblTotalCount.Padding = new Padding(5, 3, 5, 0);

            // 创建页大小标签
            LabelControl lblPageSize = new LabelControl();
            lblPageSize.Text = "每页显示:";
            lblPageSize.AutoSize = true;
            lblPageSize.Padding = new Padding(5, 3, 5, 0);

            // 添加控件到窗体底部
            FlowLayoutPanel paginationPanel = new FlowLayoutPanel();
            paginationPanel.Dock = DockStyle.Bottom;
            paginationPanel.Height = 40;
            paginationPanel.Padding = new Padding(5);
            paginationPanel.FlowDirection = FlowDirection.LeftToRight;

            // 添加控件到面板
            paginationPanel.Controls.Add(btnFirst);
            paginationPanel.Controls.Add(button4); // 上一页按钮
            paginationPanel.Controls.Add(lblPageInfo);
            paginationPanel.Controls.Add(button5); // 下一页按钮
            paginationPanel.Controls.Add(btnLast);
            paginationPanel.Controls.Add(lblTotalCount);
            paginationPanel.Controls.Add(lblPageSize);
            paginationPanel.Controls.Add(pageSizeCombo);

            // 添加面板到窗体
            this.Controls.Add(paginationPanel);

            // 调整原有按钮宽度和样式
            button4.Width = 60;
            button4.Text = "上一页";
            button5.Width = 60;
            button5.Text = "下一页";
        }

        /// <summary>
        /// 初始化物料群组下拉框
        /// </summary>
        private void InitMaterialGroupComboBox()
        {
            // 添加物料群组选项
            comboBox1.Items.Clear();
            comboBox1.Items.Add(" ");
            comboBox1.Items.Add("原材料");
            comboBox1.Items.Add("半成品");
            comboBox1.Items.Add("成品");
            comboBox1.Items.Add("其他");
            comboBox1.SelectedIndex = 0;
        }

        /// <summary>
        /// 页大小改变事件
        /// </summary>
        private void PageSizeCombo_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
                ComboBoxEdit combo = sender as ComboBoxEdit;
                if (combo != null && int.TryParse(combo.EditValue.ToString(), out int newPageSize))
                {
                    pageSize = newPageSize;
                    pageIndex = 1; // 重置为第一页
                    LoadData();
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"修改页容量异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 首页按钮点击事件
        /// </summary>
        private void BtnFirst_Click(object sender, EventArgs e)
        {
            try
            {
                if (pageIndex > 1)
                {
                    pageIndex = 1;
                    LoadData();
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"翻页操作异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 尾页按钮点击事件
        /// </summary>
        private void BtnLast_Click(object sender, EventArgs e)
        {
            try
            {
                int totalPages = (int)Math.Ceiling((double)totalCount / pageSize);
                if (pageIndex < totalPages)
                {
                    pageIndex = totalPages;
                    LoadData();
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"翻页操作异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 加载产品物料数据
        /// </summary>
        private async void LoadData()
        {
            try
            {
                // 构建查询参数
                string productTypeValue = string.Empty;
                if (comboBox1.SelectedIndex > 0)
                {
                    // 将选择的物料群组转换为对应的数字类型
                    switch (comboBox1.SelectedItem.ToString())
                    {
                        case "原材料":
                            productTypeValue = "1";
                            break;
                        case "半成品":
                            productTypeValue = "2";
                            break;
                        case "成品":
                            productTypeValue = "3";
                            break;
                        case "其他":
                            productTypeValue = "4";
                            break;
                    }
                    Console.WriteLine($"转换物料类型: \"{comboBox1.SelectedItem}\" -> {productTypeValue}");
                }

                // 获取编号和名称的查询值
                string productCode = textEdit1.Text.Trim();
                string productName = textEdit2.Text.Trim();
                
                // 查询前记录日志
                Console.WriteLine($"开始查询: 页码={pageIndex}, 每页数量={pageSize}");
                Console.WriteLine($"查询条件: 产品类型值={productTypeValue}, 产品编号=\"{productCode}\", 产品名称=\"{productName}\"");

                // 构建API URL基础部分，包含分页参数
                string url = $"http://47.110.243.157:5052/api/ProductItem/GetProductItem?pageindex={pageIndex}&pagesize={pageSize}";
                
                // 添加产品类型参数
                if (!string.IsNullOrEmpty(productTypeValue))
                {
                    url += $"&Producttype={HttpUtility.UrlEncode(productTypeValue)}";
                    Console.WriteLine($"添加产品类型查询条件: Producttype={productTypeValue}");
                }
                
                // 添加产品编号查询参数
                if (!string.IsNullOrEmpty(productCode))
                {
                    url += $"&Productitemcode={HttpUtility.UrlEncode(productCode)}";
                    Console.WriteLine($"添加产品编码查询条件: Productitemcode={productCode}");
                }
                
                // 添加产品名称查询参数
                if (!string.IsNullOrEmpty(productName))
                {
                    url += $"&Productitemname={HttpUtility.UrlEncode(productName)}";
                    Console.WriteLine($"添加产品名称查询条件: Productitemname={productName}");
                }
                
                Console.WriteLine($"完整请求URL: {url}");

                try
                {
                    using (HttpClient client = new HttpClient())
                    {
                        // 设置超时时间
                        client.Timeout = TimeSpan.FromSeconds(30);
                        
                        // 记录请求开始时间
                        DateTime startTime = DateTime.Now;
                        
                        // 发送GET请求
                        HttpResponseMessage response = await client.GetAsync(url);
                        
                        // 记录请求结束时间
                        TimeSpan requestTime = DateTime.Now - startTime;
                        Console.WriteLine($"API请求耗时: {requestTime.TotalMilliseconds}ms");
                        
                        // 检查响应状态
                        if (response.IsSuccessStatusCode)
                        {
                            // 读取响应内容
                            string responseContent = await response.Content.ReadAsStringAsync();
                            Console.WriteLine("API响应成功，开始解析数据");
                            
                            // 反序列化响应结果
                            var result = JsonConvert.DeserializeObject<ProductItemDto>(responseContent);
                            
                            if (result == null)
                            {
                                XtraMessageBox.Show("无法解析返回的数据", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                return;
                            }
                            
                            if (result.Code != "200")
                            {
                                XtraMessageBox.Show($"获取数据失败: {result.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                return;
                            }
                            
                            // 更新总记录数
                            totalCount = result.TotalCount;
                            Console.WriteLine($"获取到总记录数: {totalCount}");
                            
                            // 绑定数据到GridControl
                            gridControl1.DataSource = result.PageData;
                            Console.WriteLine($"成功加载数据: {(result.PageData != null ? result.PageData.Count : 0)}条记录");
                            
                            // 更新分页信息
                            UpdatePageInfo();
                        }
                        else
                        {
                            // 读取错误响应
                            string errorContent = await response.Content.ReadAsStringAsync();
                            XtraMessageBox.Show($"获取数据失败，HTTP状态码: {response.StatusCode}\n{errorContent}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            Console.WriteLine($"API请求失败: {response.StatusCode}, 响应内容: {errorContent}");
                        }
                    }
                }
                catch (Exception ex)
                {
                    XtraMessageBox.Show($"网络请求异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    Console.WriteLine($"网络请求异常: {ex.Message}\n{ex.StackTrace}");
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"加载数据异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Console.WriteLine($"加载数据异常: {ex.Message}\n{ex.StackTrace}");
            }
        }

        /// <summary>
        /// 更新页码信息
        /// </summary>
        private void UpdatePageInfo()
        {
            int totalPages = (int)Math.Ceiling((double)totalCount / pageSize);

            // 更新为简单标题，不包含页码信息
            this.Text = "产品物料管理";

            // 更新分页信息标签
            LabelControl lblPageInfo = this.Controls.Find("lblPageInfo", true).FirstOrDefault() as LabelControl;
            if (lblPageInfo != null)
            {
                lblPageInfo.Text = $"{pageIndex}/{totalPages}";
            }

            // 更新总记录数标签
            LabelControl lblTotalCount = this.Controls.Find("lblTotalCount", true).FirstOrDefault() as LabelControl;
            if (lblTotalCount != null)
            {
                lblTotalCount.Text = $"共{totalCount}条记录";
            }

            // 设置按钮状态
            SimpleButton btnFirst = this.Controls.OfType<SimpleButton>().FirstOrDefault(b => b.Text == "首页");
            SimpleButton btnLast = this.Controls.OfType<SimpleButton>().FirstOrDefault(b => b.Text == "尾页");

            if (btnFirst != null) btnFirst.Enabled = pageIndex > 1;
            if (btnLast != null) btnLast.Enabled = pageIndex < totalPages;
            button4.Enabled = pageIndex > 1;
            button5.Enabled = pageIndex < totalPages;
        }

        /// <summary>
        /// 查询按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                // 获取查询条件，根据需要打印日志方便调试
                string productCode = textEdit1.Text.Trim();
                string productName = textEdit2.Text.Trim();
                string productType = comboBox1.SelectedIndex > 0 ? comboBox1.SelectedItem.ToString() : string.Empty;
                
                Console.WriteLine($"执行查询: 产品编号=\"{productCode}\", 产品名称=\"{productName}\", 产品类型=\"{productType}\"");
                
                pageIndex = 1; // 重置为第一页
                LoadData();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"查询操作异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 上一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                if (pageIndex > 1)
                {
                    pageIndex--;
                    LoadData();
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"翻页操作异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 下一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            try
            {
                int totalPages = (int)Math.Ceiling((double)totalCount / pageSize);
                if (pageIndex < totalPages)
                {
                    pageIndex++;
                    LoadData();
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"翻页操作异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 物料群组下拉框选择
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                // 如果不是选择第一项（请选择群组类型），则自动触发查询
                if (comboBox1.SelectedIndex > 0)
                {
                    pageIndex = 1; // 重置为第一页
                    LoadData();
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"查询操作异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 配置GridView列
        /// </summary>
        private void ConfigureGridViewColumns()
        {
            try
            {
                // 清除现有列
                gridView1.Columns.Clear();

                // 添加序号列
                gridView1.Columns.Add(new DevExpress.XtraGrid.Columns.GridColumn
                {
                    Caption = "序号",
                    FieldName = "Id",
                    Visible = true,
                    VisibleIndex = 0,
                    Width = 60
                });

                // 添加编码列
                gridView1.Columns.Add(new DevExpress.XtraGrid.Columns.GridColumn
                {
                    Caption = "编号",
                    FieldName = "Productitemcode",
                    Visible = true,
                    VisibleIndex = 1,
                    Width = 100
                });

                // 添加名称列
                gridView1.Columns.Add(new DevExpress.XtraGrid.Columns.GridColumn
                {
                    Caption = "名称",
                    FieldName = "Productitemname",
                    Visible = true,
                    VisibleIndex = 2,
                    Width = 120
                });

                // 添加规格型号列
                gridView1.Columns.Add(new DevExpress.XtraGrid.Columns.GridColumn
                {
                    Caption = "规格型号",
                    FieldName = "Productitemspecification",
                    Visible = true,
                    VisibleIndex = 3,
                    Width = 100
                });

                // 添加单位列
                gridView1.Columns.Add(new DevExpress.XtraGrid.Columns.GridColumn
                {
                    Caption = "单位",
                    FieldName = "Productitemunit",
                    Visible = true,
                    VisibleIndex = 4,
                    Width = 60
                });

                // 添加预警值列
                gridView1.Columns.Add(new DevExpress.XtraGrid.Columns.GridColumn
                {
                    Caption = "预警值",
                    FieldName = "Productitemwarningvalue",
                    Visible = true,
                    VisibleIndex = 5,
                    Width = 60
                });

                // 添加群组名称列
                gridView1.Columns.Add(new DevExpress.XtraGrid.Columns.GridColumn
                {
                    Caption = "群组名称",
                    FieldName = "Materialgroupid",
                    Visible = true,
                    VisibleIndex = 6,
                    Width = 100
                });

                // 添加群组类型列
                DevExpress.XtraGrid.Columns.GridColumn groupTypeColumn = new DevExpress.XtraGrid.Columns.GridColumn
                {
                    Caption = "群组类型",
                    FieldName = "Producttype",
                    Visible = true,
                    VisibleIndex = 7,
                    Width = 80
                };
                
                // 自定义显示逻辑，将数字转换为对应的群组类型文字
                groupTypeColumn.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom;
                groupTypeColumn.DisplayFormat.Format = new ProductTypeFormatter();
                gridView1.Columns.Add(groupTypeColumn);

                // 添加描述列
                gridView1.Columns.Add(new DevExpress.XtraGrid.Columns.GridColumn
                {
                    Caption = "描述",
                    FieldName = "Productitemdescribe",
                    Visible = true,
                    VisibleIndex = 8,
                    Width = 150
                });

                // 添加创建人列
                gridView1.Columns.Add(new DevExpress.XtraGrid.Columns.GridColumn
                {
                    Caption = "创建人",
                    FieldName = "CreatedBy",
                    Visible = true,
                    VisibleIndex = 9,
                    Width = 80
                });

                // 添加创建时间列
                gridView1.Columns.Add(new DevExpress.XtraGrid.Columns.GridColumn
                {
                    Caption = "创建时间",
                    FieldName = "CreatedTime",
                    Visible = true,
                    VisibleIndex = 10,
                    Width = 120
                });

                // 添加修改时间列
                gridView1.Columns.Add(new DevExpress.XtraGrid.Columns.GridColumn
                {
                    Caption = "修改时间",
                    FieldName = "UpdatedTime",
                    Visible = true,
                    VisibleIndex = 11,
                    Width = 120
                });

                // 添加修改按钮列
                DevExpress.XtraGrid.Columns.GridColumn editColumn = new DevExpress.XtraGrid.Columns.GridColumn
                {
                    Caption = "修改",
                    VisibleIndex = 12,
                    Width = 60,
                    Visible = true,
                    UnboundType = DevExpress.Data.UnboundColumnType.Object,
                    Name = "EditColumn"
                };
                
                // 创建修改按钮编辑器
                repositoryItemButtonEdit1 = new DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit();
                repositoryItemButtonEdit1.AutoHeight = false;
                repositoryItemButtonEdit1.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.HideTextEditor;
                repositoryItemButtonEdit1.Buttons.Clear();
                repositoryItemButtonEdit1.Buttons.Add(new DevExpress.XtraEditors.Controls.EditorButton(
                    DevExpress.XtraEditors.Controls.ButtonPredefines.Glyph)
                {
                    Caption = "修改",
                    Kind = DevExpress.XtraEditors.Controls.ButtonPredefines.Glyph,
                    Appearance = { TextOptions = { HAlignment = DevExpress.Utils.HorzAlignment.Center } }
                });
                repositoryItemButtonEdit1.ButtonsStyle = DevExpress.XtraEditors.Controls.BorderStyles.Simple;
                repositoryItemButtonEdit1.ButtonClick += repositoryItemButtonEdit1_ButtonClick;
                
                // 添加编辑器到GridControl的RepositoryItems集合
                gridControl1.RepositoryItems.Add(repositoryItemButtonEdit1);
                
                // 设置列的编辑器
                editColumn.ColumnEdit = repositoryItemButtonEdit1;
                gridView1.Columns.Add(editColumn);

                // 添加删除按钮列
                DevExpress.XtraGrid.Columns.GridColumn deleteColumn = new DevExpress.XtraGrid.Columns.GridColumn
                {
                    Caption = "删除",
                    VisibleIndex = 13,
                    Width = 60,
                    Visible = true,
                    UnboundType = DevExpress.Data.UnboundColumnType.Object,
                    Name = "DeleteColumn"
                };
                
                // 创建删除按钮编辑器
                repositoryItemButtonEdit2 = new DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit();
                repositoryItemButtonEdit2.AutoHeight = false;
                repositoryItemButtonEdit2.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.HideTextEditor;
                repositoryItemButtonEdit2.Buttons.Clear();
                repositoryItemButtonEdit2.Buttons.Add(new DevExpress.XtraEditors.Controls.EditorButton(
                    DevExpress.XtraEditors.Controls.ButtonPredefines.Glyph)
                {
                    Caption = "删除",
                    Kind = DevExpress.XtraEditors.Controls.ButtonPredefines.Glyph,
                    Appearance = { TextOptions = { HAlignment = DevExpress.Utils.HorzAlignment.Center } }
                });
                repositoryItemButtonEdit2.ButtonsStyle = DevExpress.XtraEditors.Controls.BorderStyles.Simple;
                repositoryItemButtonEdit2.ButtonClick += repositoryItemButtonEdit2_ButtonClick;
                
                // 添加编辑器到GridControl的RepositoryItems集合
                gridControl1.RepositoryItems.Add(repositoryItemButtonEdit2);
                
                // 设置列的编辑器
                deleteColumn.ColumnEdit = repositoryItemButtonEdit2;
                gridView1.Columns.Add(deleteColumn);

                // 设置GridView的选项
                gridView1.OptionsBehavior.Editable = true; // 允许编辑
                gridView1.OptionsView.ShowGroupPanel = false;
                gridView1.OptionsView.ShowIndicator = false;
                
                // 启用自定义按钮单元格
                gridView1.OptionsBehavior.AllowFixedGroups = DevExpress.Utils.DefaultBoolean.False;
                gridView1.OptionsBehavior.EditorShowMode = DevExpress.Utils.EditorShowMode.MouseUp; // 使用MouseUp而不是Click
                
                // 添加行点击事件处理
                gridView1.RowCellClick -= GridView1_RowCellClick; // 先移除再添加，避免重复
                gridView1.RowCellClick += GridView1_RowCellClick;
                
                // 设置每列的可编辑状态
                foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridView1.Columns)
                {
                    if (column.Name == "EditColumn" || column.Name == "DeleteColumn")
                    {
                        column.OptionsColumn.AllowEdit = true;
                    }
                    else
                    {
                        column.OptionsColumn.AllowEdit = false;
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"配置网格列异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 行单元格点击事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GridView1_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            try
            {
                Console.WriteLine($"单元格点击: 列名={e.Column.Name}, 列标题={e.Column.Caption}");
                
                // 检查是否点击了修改或删除按钮列
                if (e.Column.Name == "EditColumn")
                {
                    // 获取当前行的ID
                    var rowHandle = e.RowHandle;
                    var id = gridView1.GetRowCellValue(rowHandle, "Id");
                    Console.WriteLine($"点击修改按钮: ID={id}");
                    
                    // 调用修改按钮处理方法
                    XtraMessageBox.Show($"修改功能暂未实现，选中ID: {id}", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else if (e.Column.Name == "DeleteColumn")
                {
                    // 获取当前行的ID
                    var rowHandle = e.RowHandle;
                    var id = gridView1.GetRowCellValue(rowHandle, "Id");
                    Console.WriteLine($"点击删除按钮: ID={id}");
                    
                    // 调用删除按钮处理方法
                    XtraMessageBox.Show($"删除功能暂未实现，选中ID: {id}", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"处理行点击事件异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 修改按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void repositoryItemButtonEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                // 获取当前选中行的数据
                var view = gridControl1.MainView as DevExpress.XtraGrid.Views.Grid.GridView;
                if (view != null && view.FocusedRowHandle >= 0)
                {
                    var id = view.GetRowCellValue(view.FocusedRowHandle, "Id");
                    Console.WriteLine($"修改按钮点击: ID={id}");
                    XtraMessageBox.Show($"修改功能暂未实现，选中ID: {id}", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    XtraMessageBox.Show("请先选择要修改的记录", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"修改操作异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 删除按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void repositoryItemButtonEdit2_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                // 获取当前选中行的数据
                var view = gridControl1.MainView as DevExpress.XtraGrid.Views.Grid.GridView;
                if (view != null && view.FocusedRowHandle >= 0)
                {
                    var id = view.GetRowCellValue(view.FocusedRowHandle, "Id");
                    Console.WriteLine($"删除按钮点击: ID={id}");
                    XtraMessageBox.Show($"删除功能暂未实现，选中ID: {id}", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    XtraMessageBox.Show("请先选择要删除的记录", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"删除操作异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 新增按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            // 新增按钮功能暂不实现
            XtraMessageBox.Show("新增功能暂未实现", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        /// <summary>
        /// 导出按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            // 导出按钮功能暂不实现
            XtraMessageBox.Show("导出功能暂未实现", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }

    // 自定义格式化器，将产品类型数字转换为文字
    public class ProductTypeFormatter : IFormatProvider, ICustomFormatter
    {
        public object GetFormat(Type formatType)
        {
            if (formatType == typeof(ICustomFormatter))
                return this;
            return null;
        }

        public string Format(string format, object arg, IFormatProvider formatProvider)
        {
            if (arg == null)
                return "-";
            
            if (arg is int productType)
            {
                switch (productType)
                {
                    case 1: return "原材料";
                    case 2: return "半成品";
                    case 3: return "成品";
                    case 4: return "其他";
                    default: return $"{arg}";
                }
            }
            
            // 对于其他类型的值，尝试转换为整数
            if (int.TryParse(arg.ToString(), out int value))
            {
                switch (value)
                {
                    case 1: return "原材料";
                    case 2: return "半成品";
                    case 3: return "成品";
                    case 4: return "其他";
                    default: return $"{arg}";
                }
            }
            
            return arg.ToString();
        }
    }
}